var http = require("http");
var httpProxy = require("http-proxy");
var url = require('url');
// var fs = require('fs');
// var mine = require('./mine').types;
// var path = require('path');

var PORT = 80;
var FRONTEND_PORT = 8080
var BACKEND_PORT = 8081

var FRONTEND_CONTEXT = "/dist"
var frontendProxy = httpProxy.createProxyServer({
    target: 'http://localhost:'+FRONTEND_PORT,
    // 下面的设置用于https
    // ssl: {
    //     key: fs.readFileSync('server_decrypt.key', 'utf8'),
    //     cert: fs.readFileSync('server.crt', 'utf8')
    // },
    // secure: false
});
frontendProxy.on('error', function (err, req, res) {
    res.writeHead(500, {
        'content-type': 'text/plain'
    });
    console.log(err);
    res.end('Something went wrong. And we are reporting a custom error message.');
})

var backendProxy = httpProxy.createProxyServer({
    target: 'http://localhost:'+BACKEND_PORT,
    // 下面的设置用于https
    // ssl: {
    //     key: fs.readFileSync('server_decrypt.key', 'utf8'),
    //     cert: fs.readFileSync('server.crt', 'utf8')
    // },
    // secure: false
});
backendProxy.on('error', function (err, req, res) {
    res.writeHead(500, {
        'content-type': 'text/plain'
    });
    console.log(err);
    res.end('Something went wrong. And we are reporting a custom error message.');
})

var app = http.createServer(function (req, res) {
    var pathname = url.parse(req.url).pathname;
    console.log(pathname);
    if (pathname.indexOf(FRONTEND_CONTEXT) > -1 || pathname == '/' || pathname.endsWith('.ico')) {
        frontendProxy.web(req, res);
        return;
    }

    backendProxy.web(req, res);
});

app.listen(PORT, function () {
    console.log("server is running at %d", PORT);
})